<template>
  <div class="login-page">
    <div class="back">
      <!-- .native绑定组件的原生事件，属于组件根元素 -->
      <!-- $router.back() 返回上一次访问路由，forward go -->
      <geek-icon @click.native="$router.back()" name="esay-close"></geek-icon>
    </div>
    <h3 class="title">短信登录</h3>
    <!-- 表单 -->
    <van-form @submit="onSubmit" ref="form">
      <van-field
        placeholder="请输入手机号"
        v-model="form.mobile"
        :rules="rules.mobile"
        name="mobile"
      ></van-field>
      <van-field
        placeholder="请输入验证码"
        v-model="form.code"
        :rules="rules.code"
        name="code"
      >
        <template #button>
          <span class="send" @click="send">{{
            second > 0 ? `${second}秒后重新发送` : '获取验证码'
          }}</span>
        </template>
      </van-field>
      <van-button native-type="submit">登录</van-button>
    </van-form>
  </div>
</template>
<script>
import { loginApi, getCodeApi } from '@/api/index'
export default {
  name: 'LoginPage',
  data () {
    return {
      second: 0, // 倒计时秒数
      timer: null, // 定时器ID
      form: {
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对' }
        ],
        code: [
          { required: true, message: '请输入手机号' },
          { pattern: /^\d{6}$/, message: '验证码是6个数字' }
        ]
      }
    }
  },
  methods: {
    // 表单提交 登录
    async onSubmit (values) {
      // console.log('submit', values)
      const [err, res] = await loginApi(values)
      if (err) return this.$toast.fail('登录失败')
      // console.log(res)
      this.$store.commit('user/setToken', res.data.data.token) // 存token
      this.$router.push(this.$route.query.returnUrl || '/')
    },
    // 发送验证码
    async send () {
      if (this.second > 0) return // 不允许重复点击

      // 调用接口 发送验证码之前 验证手机号格式是否正确
      await this.$refs.form.validate('mobile') // 加上  await   验证不通过时,不执行后续操作
      // 发送验证码
      const [err] = await getCodeApi(this.form.mobile)
      if (err) return this.$toast.fail('发送失败,请稍后再试')

      this.second = 60

      this.timer = setInterval(() => {
        this.second--
        if (this.second <= 0) clearInterval(this.timer)
      }, 1000)
    }
  }
}
</script>
<style scoped lang="less">
.login-page {
  padding: 0 32px;
  .back {
    height: 60px;
    display: flex;
    align-items: center;
    .geek-icon {
      font-size: 20px;
      color: #ccc;
      position: relative;
      left: -15px;
    }
  }
  .title {
    font-size: 22px;
    line-height: 1;
    padding: 30px 0;
  }
  .van-cell {
    padding: 20px 0;
    &::after {
      left: 0;
      right: 0;
    }
  }
  .van-button {
    width: 100%;
    margin-top: 40px;
    height: 50px;
    color: #fff;
    font-size: 16px;
    border: none;
    background: linear-gradient(to right, #ff9999, #ffa179);
  }
}
.send {
  font-size: 12px;
  color: #a5a6ab;
}
</style>
